package com.neuedu.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.neuedu.bean.UserS;

public class ObjectExample {

	public static void main(String[] args) {
		/*addFile();*/
		readFile();

	}
	/**
	 * 读取文件中数据
	 */
	public static void readFile() {
		File file=new File("e:/user.txt");
		
		FileInputStream fis=null;
		
		//对象输出流
		ObjectInputStream ois=null;
		
		
		try {
			fis=new FileInputStream(file);
			ois=new ObjectInputStream(fis);
			
			UserS user1=(UserS)ois.readObject();
			UserS user2=(UserS)ois.readObject();
			System.out.println(user1);
			System.out.println(user2);
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally {
			try {
				ois.close();
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
		}
		
	}
	
	/**
	 * 添加数据到文件user.txt （E）
	 */
	public static void addFile()  {
		File file=new File("e:/user.txt");
		
		FileOutputStream fos=null;
		
		//对象输出流
		ObjectOutputStream oos=null;
		
		
		
		
		try {
			fos=new FileOutputStream(file);
			oos=new ObjectOutputStream(fos);
			
			//对象
			UserS user1=new UserS();
			user1.setUserid(1105);
			user1.setUsername("lili");
			user1.setUserpwd("123");
			user1.setAge(45);
			
			oos.writeObject(user1);
			
			UserS user2=new UserS();
			user2.setUserid(1107);
			user2.setUsername("anan");
			user2.setUserpwd("789");
			user2.setAge(78);
			
			oos.writeObject(user2);
			oos.flush();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				oos.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		
	}

}
